package com.example.zhunongzonghe.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.zhunongzonghe.common.Result;
import com.example.zhunongzonghe.entity.ZnUsers;
import com.example.zhunongzonghe.service.IZnUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/Login")
public class LoginController {
    @Autowired
    private IZnUsersService iZnUsersService;

    @RequestMapping("/hello")
    @PreAuthorize("hasAuthority('system:test:list')")
    public String hello(){
        return "欢迎，开始你新的学习旅程吧";
    }

    /**
     * 用户登录
     * @param znUsers
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody ZnUsers znUsers){
        LambdaQueryWrapper<ZnUsers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnUsers::getUserName,znUsers.getUserName());
        ZnUsers userInfo = iZnUsersService.getOne(queryWrapper);
        Map<String,Object> map = iZnUsersService.login(znUsers);
        // 登录成功
        userInfo.setId(null);
        userInfo.setPassword(null);
        map.put("userinfo", userInfo);
        return new Result(true, "登录成功", 200, map);

    }
    @PostMapping("/register")
    public Result register(@RequestBody ZnUsers znUsers){
        if (znUsers.getUserName() == null)  return new Result(false,"数据异常",400);
        ZnUsers isunll = iZnUsersService.getUserName(znUsers.getUserName());
        if (isunll==null){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            znUsers.setPassword(encoder.encode(znUsers.getPassword()));
            znUsers.setRole("user");
            znUsers.setStatus(0);
            znUsers.setCreateTime(LocalDateTime.now());
            iZnUsersService.save(znUsers);
            return new Result(true,"成功",200);
        }else {
            return new Result(false,"用户名已存在",400);
        }


    }

    @RequestMapping("/cx")
    public Result sss(Principal principal){
        System.out.println("测试:"+principal.getName());
        LambdaQueryWrapper<ZnUsers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnUsers::getUserName,principal.getName());
        ZnUsers znUsers = iZnUsersService.getOne(queryWrapper);
        return new Result(true,"查询成功",200,znUsers);
    }
    /**
     * 用户退出登录
     * @return
     */
    @RequestMapping("/logout")
    public Result logOut(){
        return iZnUsersService.logout();
    }
}
